package org.micode.common.ntp;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo;
import org.apache.commons.net.ntp.TimeStamp;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

@Slf4j
public class NtpClient {

    private NTPUDPClient ntpudpClient = null;
    private InetAddress inetAddress = null;
    private boolean isInit = false;
    private String ntpServerHostname;

    public void initNtpClient(String ntpServer, int timeout) {
        this.ntpudpClient = new NTPUDPClient();
        this.ntpudpClient.setDefaultTimeout(timeout);
        try {
            this.inetAddress = InetAddress.getByName(ntpServer);
            this.ntpServerHostname = ntpServer;
            this.isInit = true;
        } catch(UnknownHostException ex) {
            log.warn("The NTP server not found: {}", ntpServer, ex);
            this.isInit = false;
        }
    }

    public Date getNtpServerTime() {
        if (this.isInit) {
            try {
                TimeInfo timeInfo = this.ntpudpClient.getTime(this.inetAddress);
                TimeStamp timeStamp = timeInfo.getMessage().getTransmitTimeStamp();
                return timeStamp.getDate();
            } catch(IOException ex) {
                log.warn("IOException for getNtpServerTime({})", this.ntpServerHostname, ex);
            }
        }
        return null;
    }

    public void stopNtpClient() {
        this.isInit = false;
        if (null != this.ntpudpClient) {
            this.ntpudpClient.close();
        }
    }

}
